/**
   Copyright 2011 Фроловский А. В.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
   
   This file is a part of MyStats project
 */

package foo.mystats;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import foo.mystats.contentprovider.RowContentProvider;
import foo.mystats.db.RowTable;
import foo.mystats.model.DataType;

public class RowEditActivity extends ActionBarActivity {
  EditText name;
  EditText description;
  CheckBox isTimeNeeded;
  Spinner dataType;

  private Uri rowUri;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.setContentView(R.layout.row_edit);

    DataType[] dataTypes = new DataType[] {
        new DataType(DataType.INTEGER, getString(R.string.datatype_integer)),
        new DataType(DataType.REAL, getString(R.string.datatype_real)),
        new DataType(DataType.STRING, getString(R.string.datatype_string)),
        new DataType(DataType.BOOLEAN, getString(R.string.datatype_boolean)),
        new DataType(DataType.TIME, getString(R.string.datatype_time))
    };

    ArrayAdapter<DataType> adapter = new ArrayAdapter<DataType>(this, android.R.layout.simple_spinner_item, dataTypes);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    dataType = (Spinner) findViewById(R.id.row_edit_datatype_spinner);
    dataType.setAdapter(adapter);

    name = (EditText) findViewById(R.id.row_edit_name_edittext);
    description = (EditText) findViewById(R.id.row_edit_description_edittext);
    isTimeNeeded = (CheckBox) findViewById(R.id.row_edit_is_time_needed_checkbox);

    Bundle extras = getIntent().getExtras();
    rowUri = (savedInstanceState == null) ? null : (Uri) savedInstanceState.getParcelable("row_uri");
    if (extras != null) {
      rowUri = extras.getParcelable("row_uri");
      fillData(rowUri);
    }

    boolean isNew = (extras == null);
    isTimeNeeded.setEnabled(isNew);
    dataType.setEnabled(isNew);

    this.setTitle(isNew ? R.string.row_edit_add_row : R.string.row_edit_edit_row);
  }

  private void fillData(Uri uri) {
    String[] projection = {
        RowTable.COLUMN_DATA_TYPE,
        RowTable.COLUMN_DESCRIPTION,
        RowTable.COLUMN_IS_TIME_NEEDED,
        RowTable.COLUMN_NAME,
    };

    Cursor c = getContentResolver().query(uri, projection, null, null, null);
    if (c != null) {
      c.moveToFirst();

      name.setText(c.getString(c.getColumnIndexOrThrow(RowTable.COLUMN_NAME)));
      description.setText(c.getString(c.getColumnIndexOrThrow(RowTable.COLUMN_DESCRIPTION)));
      isTimeNeeded.setChecked(c.getInt(c.getColumnIndexOrThrow(RowTable.COLUMN_IS_TIME_NEEDED)) == 1);

      // todo иди в статик
      DataType[] dataTypes = new DataType[] {
          new DataType(DataType.INTEGER, getString(R.string.datatype_integer)),
          new DataType(DataType.REAL, getString(R.string.datatype_real)),
          new DataType(DataType.STRING, getString(R.string.datatype_string)),
          new DataType(DataType.BOOLEAN, getString(R.string.datatype_boolean)),
          new DataType(DataType.TIME, getString(R.string.datatype_time))
      };

      int type = c.getInt(c.getColumnIndexOrThrow(RowTable.COLUMN_DATA_TYPE));
      for (int i = 0; i < dataTypes.length; i++) {
        if (dataTypes[i].getType() == type) {
          dataType.setSelection(i);
          break;
        }
      }

      c.close();
    }
  }

  public void onAddClick(View v) {
    saveState();
    this.finish();
  }

  private void saveState() {
    ContentValues values = new ContentValues();
    values.put(RowTable.COLUMN_NAME, name.getText().toString());
    values.put(RowTable.COLUMN_DESCRIPTION, description.getText().toString());
    values.put(RowTable.COLUMN_DATA_TYPE, ((DataType) dataType.getSelectedItem()).getType());
    values.put(RowTable.COLUMN_IS_TIME_NEEDED, isTimeNeeded.isChecked() ? 1 : 0);

    // todo что будет при ошибках вставки?
    // SQLiteConstraintException - неуникальное имя
    // IllegalArgumentException - пустое имя (хотя это проще тут проверить же)

    if (rowUri == null) {
      rowUri = getContentResolver().insert(RowContentProvider.CONTENT_URI, values);
    } else {
      getContentResolver().update(rowUri, values, null, null);
    }
  }

  public void showToast(int stringResId) {
    Toast toast = Toast.makeText(getApplicationContext(), stringResId, Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.CENTER, 0, 0);
    toast.show();
  }

  public void showAlert(int stringResId) {
    new AlertDialog.Builder(this).setMessage(stringResId).show();
  }

}
